package com.android.server;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.server.jdo.ConfJdo;
import com.android.server.jdo.GroupJdo;
import com.android.server.util.PMF;
import com.google.appengine.api.datastore.Text;

@SuppressWarnings("serial")
public class AndroidServiceServlet extends HttpServlet {
	private static final String LAT = "Lat";
	private static final String LONG = "Long";
	private static final String TYPE = "type";
	private final PersistenceManagerFactory pmf = PMF.get();
	private final static String SQL = "SELECT FROM tako.wisers.com.android.jdo.StationJdo WHERE cellCode == '%s' && type == %s";
	private final static int RETURN_SIZE = 20;	
	private final static String HEADER_TEL_KEY = "tel";
	private final static String HEADER_VERSION_KEY = "version";
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			doPut(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPut(req, resp);
	}

	@Override
	public void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PersistenceManager pm = pmf.getPersistenceManager();
		String tel = req.getParameter(HEADER_TEL_KEY);
//		Query query = pm.newQuery(GroupJdo.class);
//		query.setFilter("tel == '" + tel + "'");
//		List groupList = (List) query.execute();
//		Iterator<GroupJdo> itr = groupList.iterator();
		Writer writer = resp.getWriter();;
//		if(itr.hasNext()){
//			GroupJdo gJdo = itr.next();
//			Long groupID = gJdo.getGroup();
			Query confQuery = pm.newQuery(ConfJdo.class);
			confQuery.setFilter("group == " + 1);
			List confList = (List) confQuery.execute();
			Iterator<ConfJdo> confItr = confList.iterator();
			if(confItr.hasNext()){
				ConfJdo cJdo = confItr.next();
				Text conf = cJdo.getConf();
				String version = cJdo.getVersion();
				resp.setHeader(HEADER_VERSION_KEY, version);
				try {
					writer.write(conf.getValue());
				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					writer.close();
				}
				return ;
			}
//		}
	}
}
